package com.hclc.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hclc.config.handler.bean.CommonFieldConfig;
import com.hclc.util.date.DateUtil;
import com.hclc.util.bean.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 字段填充全局处理器
 * @ClassName GlobalMetaObjectHandler
 * @Author: yurj
 * @Mail：1638234804@qq.com
 * @Date: Create in 14:24 2020/8/3
 * @version: 1.0
 */
@Slf4j
@Component
public class GlobalMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入数据填充字段方法
     * @param metaObject
     * @return void
     * @author yurj
     * @mail 1638234804@qq.com
     * @version 1.0
     * @date 2020/8/3 14:49
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 当前系统时间
        LocalDateTime now = LocalDateTime.now();
        long timestamp = DateUtil.getTimestampByLocalDateTime(now);
        // strictInsertFill方法起始版本： 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, BeanCopyUtils.convertToFieldName(CommonFieldConfig::getCreateTime), LocalDateTime.class, now);
        this.strictUpdateFill(metaObject, BeanCopyUtils.convertToFieldName(CommonFieldConfig::getUpdateTime), LocalDateTime.class, now);
        this.strictInsertFill(metaObject, BeanCopyUtils.convertToFieldName(CommonFieldConfig::getCreateTimeTimestamp), Long.class, timestamp);
        this.strictUpdateFill(metaObject, BeanCopyUtils.convertToFieldName(CommonFieldConfig::getUpdateTimeTimestamp), Long.class, timestamp);
    }

    /**
     * 更新数据填充字段方法
     * @param metaObject
     * @return void
     * @author yurj
     * @mail 1638234804@qq.com
     * @version 1.0
     * @date 2020/8/3 14:49
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 当前系统时间
        LocalDateTime now = LocalDateTime.now();
        long timestamp = DateUtil.getTimestampByLocalDateTime(now);
        this.strictUpdateFill(metaObject, BeanCopyUtils.convertToFieldName(CommonFieldConfig::getUpdateTime), LocalDateTime.class, now);
        this.strictUpdateFill(metaObject, BeanCopyUtils.convertToFieldName(CommonFieldConfig::getUpdateTimeTimestamp), Long.class, timestamp);
    }
}
